<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-row :gutter="7" style="margin-bottom: 16px; justify-content: flex-end">
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button type="primary" plain @click="openStockList"> 选择产品 </el-button>
        </div>
      </el-col>
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button type="default" plain @click="btnLie" :loading="exportLoading">
            <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
            列表字段
          </el-button>
        </div>
      </el-col>
      <el-col :span="2.5">
        <div style="text-align: left">
          <el-button
            type="default"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['system:tenant:export']"
          >
            删除
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table border :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column type="selection" fixed="left" width="60" />
      <el-table-column label="序号" prop="sort" type="index" fixed="left" width="80" />
      <el-table-column label="产品编号" align="center" prop="productCode" width="120" />
      <el-table-column label="扫码" align="center" prop="scanCode" width="120" />
      <el-table-column label="货号" align="center" prop="goodsNo" width="120" />
      <el-table-column label="产品名称" align="center" prop="productName" width="120" />
      <el-table-column label="规格" align="center" prop="specification" width="120" />
      <el-table-column label="产品属性" align="center" prop="productAttr" width="120" />
      <el-table-column label="外箱尺寸" align="center" prop="boxSize" width="120" />
      <el-table-column label="产品规格" align="center" prop="productSpec" width="120" />
      <el-table-column label="客户名称" align="center" prop="customerName" width="120" />
      <el-table-column label="赠品" align="center" prop="isGift" width="120" />
      <el-table-column label="基本单位" align="center" prop="baseUnit" width="120" />
      <el-table-column label="辅助单位" align="center" prop="altUnit" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.altUnit" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="辅助数量" align="center" prop="altQty" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.altQty" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="辅助含税单价" align="center" prop="altPriceWithTax" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.altPriceWithTax" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="辅助不含税单价" align="center" prop="altPriceWithoutTax" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.altPriceWithoutTax" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="基本含税单价" align="center" prop="basePriceWithTax" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.basePriceWithTax" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税率" align="center" prop="taxRate" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.taxRate" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="基本不含税单价" align="center" prop="basePriceWithoutTax" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.basePriceWithoutTax" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="基本数量" align="center" prop="baseQty" width="120">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input v-model="row.baseQty" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="可用库存数" align="center" prop="availableStock" width="120" />
      <el-table-column label="含税金额" align="center" prop="amountWithTax" width="120" />
      <el-table-column label="不含税金额" align="center" prop="amountWithoutTax" width="120" />
      <el-table-column label="交付日期" align="center" prop="deliveryDate" width="120" />
      <el-table-column label="备注" align="center" prop="remark" width="120" />
      <el-table-column
        label="销售提成备注"
        align="center"
        prop="salesCommissionRemark"
        width="120"
      />
      <el-table-column label="图号" align="center" prop="drawingNo" width="120" />
      <el-table-column label="标准件" align="center" prop="standardPart" width="120" />
      <el-table-column label="CNC" align="center" prop="cnc" width="120" />
      <el-table-column label="快丝" align="center" prop="fastWire" width="120" />
      <el-table-column label="单价" align="center" prop="unitPrice" width="120" />
      <el-table-column label="穿孔费" align="center" prop="punchingFee" width="120" />
      <el-table-column label="单重" align="center" prop="unitWeight" width="120" />
      <el-table-column label="长" align="center" prop="length" width="120" />
      <el-table-column label="宽" align="center" prop="width" width="120" />
      <el-table-column label="高" align="center" prop="height" width="120" />
      <el-table-column label="密度" align="center" prop="density" width="120" />
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加产品</el-button>
  </el-row>

  <el-dialog v-model="dialogVisible" title="自定义字段" width="50%" :before-close="handleClose">
    (注: 列项显示不得少于5项，最多支持自定义10个列项，灰色选中列不支持隐藏和排序)
    <div class="content">
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.productCode" label="产品编号" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.scanCode" label="扫码" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.goodsNo" label="货号" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.productName" label="产品名称" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.specification" label="规格" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.productAttr" label="产品属性" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.boxSize" label="外箱尺寸" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.productSpec" label="产品规格" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.customerName" label="客户名称" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.isGift" label="赠品" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.baseUnit" label="基本单位" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.altUnit" label="辅助单位" size="large"
      /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <ProductForm ref="selectProductRef" @success="handleProductSelected" />

</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { StockApi } from '@/api/erp/stock/stock'
import ProductForm from './ProductForm.vue'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue,
  underlineToHump
} from '@/utils'

const props = defineProps<{
  items: undefined
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  inId: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const visibleColumns = ref({
  productCode: true,
  scanCode: true,
  goodsNo: true,
  productName: true,
  specification: true,
  productAttr: true,
  boxSize: true,
  productSpec: true,
  customerName: true,
  isGift: true,
  baseUnit: true,
  altUnit: true,
  altQty: true,
  altPriceWithTax: true,
  altPriceWithoutTax: true,
  basePriceWithTax: true,
  taxRate: true,
  basePriceWithoutTax: true,
  baseQty: true,
  availableStock: true,
  amountWithTax: true,
  amountWithoutTax: true,
  deliveryDate: true,
  remark: true,
  salesCommissionRemark: true,
  drawingNo: true,
  standardPart: true,
  cnc: true,
  fastWire: true,
  unitPrice: true,
  punchingFee: true,
  unitWeight: true,
  f21421: true,
  length: true,
  width: true,
  height: true,
  density: true
})
const dialogVisible = ref(false)
const tempVisibleColumns = ref({ ...visibleColumns.value })
const selectProductRef = ref() // 物料列表 Ref
const openStockList = () => {
  selectProductRef.value.open()
}
const btnLie = () => {
  tempVisibleColumns.value = { ...visibleColumns.value }
  dialogVisible.value = true
}
const handleCancel = () => {
  dialogVisible.value = false
}
const handleConfirm = () => {
  dialogVisible.value = false
}
const handleProductSelected = (product: any) => {
  formData.value.push(product)
}
/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
// watch(
//   () => formData.value,
//   (val) => {
//     if (!val || val.length === 0) {
//       return
//     }
//     // 循环处理
//     val.forEach((item) => {
//       item.totalPrice = erpPriceMultiply(item.productPrice, item.count)
//     })
//   },
//   { deep: true }
// )

/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    sort: undefined,
    productCode: undefined,
    scanCode: undefined,
    goodsNo: undefined,
    productName: undefined,
    specification: undefined,
    productAttr: undefined,
    boxSize: undefined,
    productSpec: undefined,
    customerName: undefined,
    isGift: undefined,
    baseUnit: undefined,
    altUnit: undefined,
    altQty: undefined,
    altPriceWithTax: undefined,
    altPriceWithoutTax: undefined,
    basePriceWithTax: undefined,
    taxRate: undefined,
    basePriceWithoutTax: undefined,
    baseQty: undefined,
    availableStock: undefined,
    amountWithTax: undefined,
    amountWithoutTax: undefined,
    deliveryDate: undefined,
    remark: undefined,
    salesCommissionRemark: undefined,
    drawingNo: undefined,
    standardPart: undefined,
    cnc: undefined,
    fastWire: undefined,
    unitPrice: undefined,
    punchingFee: undefined,
    unitWeight: undefined,
    f21421: undefined,
    length: undefined,
    width: undefined,
    height: undefined,
    density: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
const onChangeWarehouse = (warehouseId, row) => {
  // 加载库存
  setStockCount(row)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.minPrice
  }
  // 加载库存
  setStockCount(row)
}

/** 加载库存 */
const setStockCount = async (row) => {
  if (!row.productId || !row.warehouseId) {
    return
  }
  const stock = await StockApi.getStock2(row.productId, row.warehouseId)
  row.stockCount = stock ? stock.count : 0
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  // productList.value = await ProductApi.getProductSimpleList()
  // warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
})
</script>
